<?php

namespace App\Http\Controllers;

use App\Model\StudentModel;
use Illuminate\Http\Request;

class StudentController extends Controller
{
    public function home(Request $request) {
        $students = StudentModel::get();
        foreach ($students as &$student){
            $student->hobby = explode(",",$student->hobby);
        }
//        return view("table",["students"=>$students]);
        return view("table",compact("students"));
    }

    public function addPage(Request $request)
    {
        $student = null;
        $id = $request->input("id");
        if($id>0){
            $student = StudentModel::find($id);
            $student->hobby = explode(",",$student->hobby);
        }
        return view("addPage",compact("student"));
    }

    public function addInfo(Request $request)
    {
        $inputs = $request->input();
        unset($inputs['_token']);
        $inputs['hobby'] = implode(',',$inputs['hobby']);
        if($inputs['id']==0){
            $headimg = $request->file("headimg");
            $inputs['img'] = $this->fileUploader("uploads",$headimg);
            $student = StudentModel::create($inputs);
            if ($student){
                return "数据库添加成功！<a href='/'> 返回首页 </a>";
            }
        }else{
            $student = StudentModel::find($inputs['id']);
            $headimg = $request->file('headimg');
            if($headimg){
                $inputs['img'] = $this->fileUploader("uploads",$headimg);
                if (file_exists($student->img)){
                    unlink($student->img);
                }
            }
            $student->update($inputs);
            return "数据库数据更新成功！<a href='/'> 返回首页 </a>";
        }
    }

    public function delStudent(Request $request)
    {
        $id = $request->input('id');
        $student = StudentModel::find($id);
        $student->delete();
        return "数据删除成功！<a href='/'> 返回首页 </a>";
    }
}
